package com.sunfeng.netty.atguigu2.nio.groupchat;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * @author sunfeng
 * @date 2021/03/23 17:26
 **/
@Slf4j
public class GroupChatServer {
    //定义属性
    private Selector selector;
    // 监听Channel
    private ServerSocketChannel listenChannel;
    // 监听端口6667
    private static final int PORT = 6667;

    //构造器
    //初始化工作
    public GroupChatServer() {
        try {
            //得到选择器
            selector = Selector.open();
            //ServerSocketChannel
            listenChannel = ServerSocketChannel.open();
            //设置非阻塞模式   这个必须设置
            listenChannel.configureBlocking(false);
            //绑定端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));

            //将该 listenChannel 注册到 selector   关注的接受事件
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void listen() {
        try {
            while (true) {
                int count = selector.select();
                System.out.println(count);
                // 有事件需要处理
                if (count > 0) {
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey selectionKey = iterator.next();
                        // 如果监听的是连接事件
                        if (selectionKey.isAcceptable()) {
                            // accept 监听新进来链接,  当accept方法返回时，它会返回一个全新的链接SocketChannel 因此, accept()方法会一直阻塞到有新连接到达
                            // Java NIO中的SocketChannel是一个连接到TCP网络套接字的通道
                            SocketChannel socketChannel = listenChannel.accept();
                            // 设置非阻塞
                            socketChannel.configureBlocking(false);
                            socketChannel.register(selector, SelectionKey.OP_READ);
                            // 提示上线
                            log.info(socketChannel.getRemoteAddress() + "成功上线");
                        }
                        //通道发送 read 事件， 即通道是可读的状态
                        if (selectionKey.isReadable()) {
                            // 处理数据读取的操作
                            readDate(selectionKey);
                        }
                        iterator.remove();

                    }
                } else {
                    log.info("等待中！！！");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("监听出现异常,异常信息为{}", e.getMessage());
        }


    }

    private void readDate(SelectionKey selectionKey) {

        //取到关联的 channel
        SocketChannel channel = null;
        try {
            // 反向获取channel
            channel = (SocketChannel) selectionKey.channel();
            //创建 buffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);

            int count = channel.read(buffer);

            if (count > 0) {
                String message = new String(buffer.array());
                message = message.trim();
                System.out.println("from 客户端的消息为：" + message);
                //向其它的客户端转发消息(去掉自己), 专门写一个方法来处理
                sendInfoToOtherClients(message, channel);
            }
        } catch (Exception e) {
            try {
                assert channel != null;
                System.out.println(channel.getRemoteAddress() + " 离线了..");
                selectionKey.channel();
                channel.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }


    }

    /**
     * 将数据转发给其他通道
     *
     * @param message
     * @param channel
     * @throws IOException
     */
    private void sendInfoToOtherClients(String message, SocketChannel channel) throws IOException {
        System.out.println("服务器转发消息中...");
        ByteBuffer buffer;
        //遍历 所有注册到 selector 上的 SocketChannel,并排除 self   所有注册的channel 排除自己
        for (SelectionKey key : selector.keys()) {
            //通过 key 取出对应的 SocketChannel
            Channel targetChannel = key.channel();
            //排除自己
            if (targetChannel instanceof SocketChannel && targetChannel != channel) {
                //转型
                SocketChannel dest = (SocketChannel) targetChannel;
                //将 msg 存储到 buffer   每次都创建buffer 浪费资源
                 buffer = ByteBuffer.wrap(message.getBytes());
                // buffer.flip();
                dest.write(buffer);
            }//将 buffer 的数据写入 通道
        }
    }

    public static void main(String[] args) {
        //创建服务器对象
        GroupChatServer groupChatServer = new GroupChatServer();
        groupChatServer.listen();

    }
}
